# -*- coding: utf-8 -*-

import json

from flask import request, render_template, url_for, jsonify, session
from flask_cors import *
from flask_login import login_user, logout_user

from . import auth
from ..models import User


@auth.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        passwd = request.form['passwd']
        user = User(username)
        if user.verify_password(passwd):
            login_user(user)
            print(request.args)
            next = request.args.get('next', '/')
            if next is None or not next.startswith("/"):
                next = url_for('complex.index')
            return jsonify(login=1, next=next)
        else:
            return jsonify(login=0)
    return render_template('auth/login.html')

@auth.route('/login2', methods=['POST', 'GET'])
@cross_origin()
def login2():
    username = request.form['username']
    passwd = request.form['passwd']
    user = User(username)
    if user.verify_password(passwd):
        login_user(user)
        print(request.args)
        next = request.args.get('next', '/')
        if next is None or not next.startswith("/"):
            next = url_for('complex.index')
        data = {}
        data['token'] = 'shzu'
        data['accountId'] = '1'
        data['userName'] = 'shzu'        
        return jsonify(login=1, isOk=True, data=data)
    else:
        return jsonify(login=0, isOk=False, msg='登录失败', cause='用户名密码错误')

# 该部分使用过滤器机制，在每次请求时检验当前用户是否登录，未登录则跳转到登录页面
@auth.route('/loginAPI', methods=['POST', 'GET'])
@cross_origin()
def loginapi():
    username = request.args.get('username')
    passwd = request.args.get('passwd')
    data={'username':username,'passwd':passwd}
    if passwd:   
        return jsonify(login=1, isOk=True, data=data)
    else:
        return jsonify(login=0, isOk=False, msg='登录失败', cause='用户名密码错误')


@auth.route('/login3', methods=['POST', 'GET'])
@cross_origin()
def login3():
    data = request.get_data()
    print(data)
    json_data = json.loads(data.decode("utf-8"))
    print(json_data)

    username = json_data['username']
    passwd = json_data['passwd']
    user = User(username)
    if user.verify_password(passwd):
        login_user(user)
        print(request.args)
        next = request.args.get('next', '/')
        if next is None or not next.startswith("/"):
            next = url_for('complex.index')
        return jsonify(login=1, next=next)
    else:
        return jsonify(login=0)


@auth.route('/logout')
@cross_origin()
def logout():
    logout_user()
    return render_template("auth/login.html")

@auth.route('/newnewpage')
@cross_origin()
def newnewpage():
    print("newpage!!!!!")
    next = request.args.get('next', '/')
    # if next is None or not next.startswith("/"):
    #     next = url_for('complex/html/index.html')
    return render_template("complex/index.html", login=1, next=next)
